<?php
/**
 * Mass message class
 * @author Hire-Experts
 * @version 1.02
 */
class he_mass_message
{
	function create_campaign($subject, $message, $levels, $subnets, $cats)
	{
		global $setting;
		
		set_time_limit(600);
		
		$levels = (array)$levels;
		$subnets = (array)$subnets;
		if($message=="" || (!$levels && !$subnets && !$cats) || !$setting['setting_mass_message_from_user']) return false;

		#generate fetch users query
		$email_query = "SELECT user_username, user_email FROM se_users";
		$conditions = array();
		
		if( $levels )
			$conditions[] = "user_level_id IN('".implode("', '", $levels)."')";
		
		if( $subnets )
			$conditions[] = "user_subnet_id IN('".implode("', '", $subnets)."')";
		
		if( $cats )
			$conditions[] = "user_profilecat_id IN('".implode("', '", $cats)."')";
		
		if( $conditions ) $email_query .= ' WHERE '.implode(' OR ', $conditions);
		
		#create campaign
		$res = he_database::query($email_query);
		$recipients_count = he_database::num_rows($res);
		$campaign_id = he_mass_message::insert_campaign($subject, $message, $setting['setting_mass_message_from_user'], $recipients_count);
		if( !$campaign_id ) return false;
		
		while( $user = he_database::fetch_row_from_resource($res) )
		{
			if( $setting['setting_mass_message_from_user']==$user['user_username'] ) continue;
			
			he_mass_message::insert_into_queue($campaign_id, $user['user_username']);
		}
		return true;
	}
	
	function insert_campaign($subject, $message, $sender, $recipient_count)
	{
		he_database::query("INSERT INTO se_mass_message_campaign SET subject='".he_database::real_escape($subject)."', message='".he_database::real_escape($message)."', sender='".he_database::real_escape($sender)."', recipient_count=$recipient_count, sent_time=UNIX_TIMESTAMP()");
		return he_database::insert_id();
	}
	
	function get_campaigns()
	{
		return he_database::fetch_array("SELECT * FROM se_mass_message_campaign");
	}
	
	function get_campaign($id)
	{
		return he_database::fetch_row("SELECT * FROM se_mass_message_campaign WHERE id=".intval($id));
	}
	
	function insert_into_queue($campaign_id, $recipient)
	{
		he_database::query("INSERT INTO se_mass_message_queue SET campaign_id=$campaign_id, recipient='".he_database::real_escape($recipient)."'");
	}
	
	function get_user_levels()
	{
		return he_database::fetch_array("SELECT level_id, level_name, level_default FROM se_levels");
	}
	
	function get_subnets()
	{
		$res = he_database::query("SELECT subnet_id, subnet_name FROM se_subnets");
		$subnet_array = array();
		while($subnet_info = he_database::fetch_row_from_resource($res))
		{
			SE_Language::_preload($subnet_info['subnet_name']);
			$subnet_array[] = $subnet_info;
		}
		
		return $subnet_array;
	}
	
	function get_profile_categories()
	{
		return he_database::fetch_array("SELECT profilecat_id, profilecat_title FROM se_profilecats WHERE !profilecat_dependency");
	}

	function update_settings($data)
	{
		global $setting;
		
		if( !$data || !is_array($data) ) return false;
		$fields = array();
		foreach ($data as $field => $value)
		{
			$fields[] = "`$field`='".he_database::real_escape($value)."'";
			$setting[$field] = $value;
		}
		$q = implode(',', $fields);
		
		he_database::query("UPDATE se_settings SET $q");
		return true;
	}
	
	function get_users($username)
	{
		global $database;
		$username = trim($username);
		if( !$username ) return array();
		
		$result = $database->database_query("SELECT user_username FROM se_users WHERE user_username LIKE '%$username%'");
		$return = array();
		while($row = $database->database_fetch_assoc($result))
		{
			$return[] = array(
				'value'=> $row['user_username'],
				'info'=> $row['user_username']
			);
		}
		return $return;
	}
	
	function send_message_from_queue($count)
	{
		$count = intval($count) ? intval($count) : 10;
		$campaigns = array();
		$senders = array();
		
		$messages = he_database::fetch_array("SELECT * FROM se_mass_message_queue ORDER BY id LIMIT $count");
		foreach ($messages as $message)
		{
			he_database::query("DELETE FROM se_mass_message_queue WHERE id={$message['id']}");
			if( !he_database::affected_rows() ) continue;
			
			if( !$campaigns[$message['campaign_id']] )
				$campaigns[$message['campaign_id']] = he_mass_message::get_campaign($message['campaign_id']);
			$campaign = $campaigns[$message['campaign_id']];
			
			if( !$senders[$campaign['sender']] )
				$senders[$campaign['sender']] = new se_user(array(0, $campaign['sender']));
			
			$sender = $senders[$campaign['sender']];
			if( !$sender->user_exists ) continue;
			
			$user = new se_user(array(0, $message['recipient']));
			if( !$user->user_exists ) continue;
			
			$subject = str_replace(array('[displayname]', '[email]'), array($user->user_info['user_displayname'], $user->user_info['user_email']), $campaign['subject']);
			$body = str_replace(array('[displayname]', '[email]'), array($user->user_info['user_displayname'], $user->user_info['user_email']), $campaign['message']);
			$sender->user_message_send($user->user_info['user_username'], $subject, $body);
			
			
		}
	}
	
	function cron()
	{
		global $setting;
		
		if( $setting['setting_mass_message_last_execute'] > time()-60 ) return;
		
		$setting['setting_mass_message_last_execute'] = time();
		he_database::query("UPDATE se_settings SET setting_mass_message_last_execute={$setting['setting_mass_message_last_execute']}");
		
		he_mass_message::send_message_from_queue($setting['setting_mass_message_per_minute']);
	}
}

?>